package com.rj.core.validation;


import com.rj.core.constant.CompareType;
import com.rj.core.exception.BaseException;
import com.rj.core.validation.constraints.NumberField;
import com.rj.util.AssertBeanUtils;
import com.rj.util.VerifyUtils;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

/**
 * @author YFX_RANLUBO
 */
public class NumFieldValidator implements ConstraintValidator<NumberField, Object> {
    /**
     * 是否允许为空
     */
    private boolean allowEmpty;
    /**
     * 属性名称
     */
    private String name;
    /**
     * 最大值
     */
    private String max;
    private String min;

    CompareType maxType;
    CompareType minType;
    /**
     * 正则表达式
     */
    private String regexp;

    /**
     * 字典key(通过key从存储拉取)
     * 与dict任意填写一个,优先取dict
     *
     * @return
     */
    private String dictKey;

    /**
     * 选项|与dictKey任意填写一个,优先取dict
     *
     * @return
     */
    private String[] dict;

    @Override
    public void initialize(NumberField checkField) {
        this.max = checkField.max();
        this.min = checkField.min();
        this.regexp = checkField.regexp();
        this.allowEmpty = checkField.empty();
        this.name = checkField.value();
        this.maxType = checkField.maxType();
        this.minType = checkField.minType();
        this.dict = checkField.dict().length > 0 ? checkField.dict() : null;
        this.dictKey = checkField.dictKey().isEmpty() ? null : checkField.dictKey();
        //dictKey todo

    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        try {
            AssertBeanUtils.check(value, name, allowEmpty)
                    .ifApply(VerifyUtils.notEmpty(regexp), (ut) -> ut.match(regexp))
                    .ifApply(VerifyUtils.notNull(dict), (ut) -> ut.in(dict))
                    .ifApply(VerifyUtils.notEmpty(min), (ut) -> ut.compare(min, minType))
                    .ifApply(VerifyUtils.notEmpty(max), (ut) -> ut.compare(max, maxType));
        } catch (BaseException e) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(e.getMessage())
                    .addConstraintViolation();
            return false;
        }

        return true;
    }
}